<template>
  <div class="question-list-container ">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="题目标题">
          <el-input
            v-model="searchForm.questionTitle"
            placeholder="请输入题目标题"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="题型">
          <el-select
            v-model="searchForm.questionType"
            placeholder="请选择题型"
            clearable
          >
            <el-option label="单选题" value="single"></el-option>
            <el-option label="多选题" value="multiple"></el-option>
            <el-option label="判断题" value="judge"></el-option>
            <el-option label="填空题" value="fill"></el-option>
            <el-option label="问答题" value="essay"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="难度">
          <el-select
            v-model="searchForm.difficulty"
            placeholder="请选择难度"
            clearable
          >
            <el-option label="简单" value="1"></el-option>
            <el-option label="较易" value="2"></el-option>
            <el-option label="中等" value="3"></el-option>
            <el-option label="较难" value="4"></el-option>
            <el-option label="困难" value="5"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-container">
      <el-button
        type="danger"
        :disabled="multipleSelection.length === 0"
        @click="handleBatchDelete"
      >
        批量删除
      </el-button>
    </div>

    <!-- 题目卡片列表 -->
    <div class="card-list">
      <el-card
        v-for="item in questionList"
        :key="item.questionId"
        class="question-card"
        shadow="hover"
        @click.native="showQuestionDetail(item.questionId)"
      >
        <div slot="header" class="card-header">
          <span class="question-title">{{ item.questionTitle }}</span>
          <el-tag :type="getQuestionTypeTag(item.questionType)" size="small">
            {{ formatQuestionType(item.questionType) }}
          </el-tag>
          <el-rate
            v-model="item.difficulty"
            disabled
            :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
            :max="5"
            :texts="['简单', '较易', '中等', '较难', '困难']"
            show-text
            class="difficulty-rate"
          />
        </div>
        <div class="card-content" v-html="truncateContent(item.questionText)"></div>
        <div class="card-footer">
          <span class="category">{{ item.categoryName }}</span>
          <span class="point">{{ item.pointName }}</span>
          <el-button
            type="text"
            icon="el-icon-delete"
            class="delete-btn"
            @click.stop="handleDelete(item.questionId)"
          >
            删除
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.current"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pagination.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
      >
      </el-pagination>
    </div>

    <!-- 题目详情对话框 -->
    <el-dialog
      :title="currentQuestion.questionTitle"
      :visible.sync="detailDialogVisible"
      width="70%"
      top="5vh"
      @opened="renderFormulas"
    >
      <div class="question-detail">
        <div class="detail-header">
          <el-tag :type="getQuestionTypeTag(currentQuestion.questionType)">
            {{ formatQuestionType(currentQuestion.questionType) }}
          </el-tag>
          <el-rate
            v-model="currentQuestion.difficulty"
            disabled
            :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
            :max="5"
            :texts="['简单', '较易', '中等', '较难', '困难']"
            show-text
          />
        </div>

        <div class="detail-content editor-content-view">
          <div class="stem " v-html="currentQuestion.questionText"></div>
          <div v-if="currentQuestion.options" class="options-section">
            <div class="section-title">选项</div>
            <div
              v-for="(option, index) in currentQuestion.options.items"
              :key="index"
              class="option-item"
            >
              <span class="option-label">{{ option.label }}.</span>
              <span class="option-content " v-html="option.content"></span>
            </div>
          </div>

          <div class="answer-section">
            <div class="section-title">正确答案</div>
            <div v-if="currentQuestion.questionType === 'multiple'" class="answer-content">
              {{ currentQuestion.correctAnswer.join(', ') }}
            </div>
            <div v-else-if="currentQuestion.questionType === 'essay'" class="answer-content">
              <div class="stem" v-html="currentQuestion.correctAnswer"></div>
            </div>
<!--            <div class="answer-plain" v-if="currentQuestion.correctAnswerPlain">-->
<!--              {{ currentQuestion.correctAnswerPlain }}-->
<!--            </div>-->
          </div>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  listQuestions,
  getQuestions,
  delQuestions,
  addQuestions,
  updateQuestions,
} from "@/api/question/manage";
import '@wangeditor/editor/dist/css/style.css'
import katex from 'katex'
import 'katex/dist/katex.min.css'

export default {
  name: 'QuestionList',
  data() {
    return {
      searchForm: {
        questionTitle: '',
        questionType: '',
        difficulty: '',
        categoryId: '',
        createName: ''
      },
      questionList: [],
      multipleSelection: [],
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      detailDialogVisible: false,
      currentQuestion: {
        questionId: '',
        questionTitle: '',
        questionText: '',
        questionType: '',
        difficulty: 0,
        categoryId: '',
        pointId: '',
        correctAnswer: '',
        correctAnswerPlain: '',
        options: {
          type: '',
          items: []
        }
      }
    }
  },
  created() {
    this.fetchQuestionList()
  },
  methods: {

    // 新增公式渲染方法
    renderFormulas() {
      this.$nextTick(() => {
        const formulas = document.querySelectorAll('[data-w-e-type="formula"]')
        formulas.forEach(element => {
          const latex = element.dataset.value
          const isInline = element.dataset.wEIsInline === 'true'

          try {
            const html = katex.renderToString(latex, {
              throwOnError: false,
              displayMode: !isInline,
              output: 'mathml'
            })

            // 创建新的容器
            const container = document.createElement(isInline ? 'span' : 'div')
            container.innerHTML = html

            // 添加自定义样式类
            if (!isInline) {
              const wrapper = document.createElement('div')
              wrapper.className = 'formula-container'
              wrapper.appendChild(container)
              element.parentNode.replaceChild(wrapper, element)
            } else {
              element.parentNode.replaceChild(container, element)
            }

          } catch (e) {
            console.error('Katex render error:', e)
            element.outerHTML = `<span style="color: red">公式错误: ${latex}</span>`
          }
        })
      })
    },
    // 获取题目列表
    fetchQuestionList() {
      const params = {
        ...this.searchForm,
        pageNum: this.pagination.current,
        pageSize: this.pagination.size
      }

      listQuestions(params).then(response => {
        if (response.code === 200) {
          this.questionList = response.rows
          this.pagination.total = response.total
        } else {
          this.$message.error(response.msg || '获取题目列表失败')
        }
      })
    },

    // 搜索题目
    handleSearch() {
      this.pagination.current = 1
      this.fetchQuestionList()
    },

    // 重置搜索条件
    resetSearch() {
      this.searchForm = {
        questionTitle: '',
        questionType: '',
        difficulty: '',
        categoryId: '',
        createName: ''
      }
      this.handleSearch()
    },

    // 显示题目详情
    showQuestionDetail(questionId) {
      getQuestions(questionId).then(response => {
        if (response.code === 200) {
          this.currentQuestion = response.data
          // 处理多选题答案
          if (this.currentQuestion.questionType === 'multiple' &&
            typeof this.currentQuestion.correctAnswer === 'string') {
            this.currentQuestion.correctAnswer = this.currentQuestion.correctAnswer.split(',')
          }
          this.detailDialogVisible = true
        } else {
          this.$message.error(response.msg || '获取题目详情失败')
        }
      })
    },

    // 删除题目
    handleDelete(questionId) {
      this.$confirm('确认删除该题目吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delQuestions(questionId).then(response => {
          if (response.code === 200) {
            this.$message.success('删除成功')
            this.fetchQuestionList()
          } else {
            this.$message.error(response.msg || '删除失败')
          }
        })
      }).catch(() => {})
    },

    // 批量删除题目
    handleBatchDelete() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请至少选择一条记录')
        return
      }

      this.$confirm(`确认删除选中的${this.multipleSelection.length}条题目吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const questionIds = this.multipleSelection.map(item => item.questionId)
        delQuestions(questionIds).then(response => {
          if (response.code === 200) {
            this.$message.success('删除成功')
            this.multipleSelection = []
            this.fetchQuestionList()
          } else {
            this.$message.error(response.msg || '删除失败')
          }
        })
      }).catch(() => {})
    },

    // 分页大小改变
    handleSizeChange(size) {
      this.pagination.size = size
      this.fetchQuestionList()
    },

    // 当前页改变
    handleCurrentChange(current) {
      this.pagination.current = current
      this.fetchQuestionList()
    },

    // 截断内容显示
    truncateContent(content) {
      if (!content) return ''
      // 移除HTML标签
      const plainText = content.replace(/<[^>]+>/g, '')
      // 截取前100个字符
      return plainText.length > 100
        ? plainText.substring(0, 100) + '...'
        : plainText
    },

    // 格式化题型显示
    formatQuestionType(type) {
      const typeMap = {
        single: '单选题',
        multiple: '多选题',
        judge: '判断题',
        fill: '填空题',
        essay: '问答题'
      }
      return typeMap[type] || type
    },

    // 获取题型对应的标签类型
    getQuestionTypeTag(type) {
      const tagMap = {
        single: 'primary',
        multiple: 'success',
        judge: 'warning',
        fill: 'info',
        essay: 'danger'
      }
      return tagMap[type] || ''
    }
  },
  watch: {
    detailDialogVisible(newVal) {
      if (newVal) {
        this.renderFormulas()
      }
    }
  }
}
</script>

<style scoped lang="scss">
.question-list-container {
  padding: 20px;
  background-color: #f5f7fa;

  .search-container {
    background-color: #fff;
    padding: 20px;
    margin-bottom: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .search-form {
      display: flex;
      flex-wrap: wrap;
    }
  }

  .action-container {
    margin-bottom: 20px;
  }

  .card-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
    gap: 20px;
    margin-bottom: 20px;

    .question-card {
      cursor: pointer;
      transition: all 0.3s;
      height: 200px;
      display: flex;
      flex-direction: column;

      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 6px 18px 0 rgba(0, 0, 0, 0.1);
      }

      .card-header {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .question-title {
          flex: 1;
          font-weight: bold;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          margin-right: 10px;
        }

        .difficulty-rate {
          margin-left: 10px;
        }
      }

      .card-content {
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 4;
        -webkit-box-orient: vertical;
        line-height: 1.5;
        color: #666;
      }

      .card-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 10px;
        font-size: 12px;
        color: #999;

        .category, .point {
          flex: 1;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .point {
          margin: 0 10px;
        }

        .delete-btn {
          color: #f56c6c;
        }
      }
    }
  }

  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }

  .question-detail {
    .detail-header {
      display: flex;
      align-items: center;
      margin-bottom: 20px;

      .el-tag {
        margin-right: 15px;
      }
    }

    .detail-content {
      max-height: 60vh;
      overflow-y: auto;
      padding-right: 10px;

      .stem {
        margin-bottom: 20px;
        line-height: 1.6;
      }

      .section-title {
        font-weight: bold;
        margin: 15px 0 10px;
        color: #333;
        font-size: 16px;
      }

      .options-section {
        .option-item {
          margin-bottom: 8px;
          line-height: 1.6;

          .option-label {
            font-weight: bold;
            margin-right: 5px;
          }
        }
      }

      .answer-section {
        margin-top: 20px;

        .answer-content {
          font-weight: bold;
          color: #67c23a;
        }

        .answer-plain {
          margin-top: 10px;
          color: #666;
        }
      }
    }
  }
}



</style>
<style>
.editor-content-view {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 20px;
  margin-top: 20px;
  background: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  line-height: 1.8;
  color: #606266;
  font-size: 15px;
  overflow-x: auto;
}

/* 优化段落和标题 */
.editor-content-view p {
  margin: 0.8em 0;
}

.editor-content-view h1 {
  font-size: 24px;
  color: #303133;
  border-bottom: 2px solid #409eff;
  padding-bottom: 8px;
  margin: 1.2em 0;
}

.editor-content-view h2 {
  font-size: 20px;
  color: #303133;
  margin: 1em 0;
}

/* 增强代码块样式 */
.editor-content-view pre {
  position: relative;
  background: #f8f8f8;
  border-radius: 6px;
  padding: 20px;
  margin: 1em 0;
  overflow: auto;
}

.editor-content-view pre:before {
  content: '代码';
  position: absolute;
  top: 0;
  right: 0;
  background: #409eff;
  color: white;
  padding: 2px 8px;
  font-size: 12px;
  border-radius: 0 6px 0 6px;
}

.editor-content-view code {
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
  background: rgba(175, 184, 193, 0.2);
  padding: 0.2em 0.4em;
  border-radius: 3px;
  font-size: 14px;
}

.editor-content-view pre code {
  background: transparent;
  padding: 0;
  font-size: 14px;
  line-height: 1.5;
}

/* 优化表格显示 */
.editor-content-view table {
  width: 100%;
  margin: 1em 0;
  border-collapse: collapse;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.editor-content-view th {
  background: #fafafa;
  font-weight: 600;
  text-align: left;
}

.editor-content-view td,
.editor-content-view th {
  border: 1px solid #e8e8e8;
  padding: 12px 15px;
  min-width: 60px;
}

.editor-content-view tr:hover {
  background-color: #f5f7fa;
}

/* 美化引用块 */
.editor-content-view blockquote {
  border-left: 4px solid #409eff;
  background: #f8f9fa;
  color: #6a737d;
  margin: 1em 0;
  padding: 12px 20px;
  border-radius: 0 6px 6px 0;
  font-style: italic;
}

/* 优化列表显示 */
.editor-content-view ul,
.editor-content-view ol {
  padding-left: 2em;
  margin: 1em 0;
}

.editor-content-view li {
  margin: 0.4em 0;
  padding-left: 0.4em;
}

.editor-content-view ul li::marker {
  color: #409eff;
}

.editor-content-view ol {
  counter-reset: item;
}

.editor-content-view ol li {
  counter-increment: item;
}

.editor-content-view ol li::before {
  content: counter(item) ". ";
  color: #409eff;
  font-weight: bold;
}

/* 数学公式优化 */
.editor-content-view .katex {
  font-size: 1.1em;
  padding: 0 0.2em;
}

/* 图片显示优化 */
.editor-content-view img {
  max-width: 100%;
  height: auto;
  display: block;
  margin: 1em auto;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 复选框样式优化 */
.editor-content-view input[type="checkbox"] {
  -webkit-appearance: none;
  appearance: none;
  width: 16px;
  height: 16px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  margin-right: 8px;
  position: relative;
  vertical-align: middle;
  cursor: pointer;
}

.editor-content-view input[type="checkbox"]:checked {
  background: #409eff;
  border-color: #409eff;
}

.editor-content-view input[type="checkbox"]:checked::after {
  content: "✓";
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  color: white;
  font-size: 12px;
}

/* 行内公式样式 */
.katex {
  font-size: 1.1em;
  padding: 0 0.2em;
  display: inline-block;
  vertical-align: middle;
}

/* 块级公式样式 */
.katex-display {
  display: block !important;
  margin: 1em 0 !important;
  text-align: center !important;
  padding: 1em !important;
  background-color: #f8f9fa !important;
  border-radius: 4px !important;
  overflow-x: auto !important;
}

/* 公式容器样式 */
.formula-container {
  margin: 1em 0;
}

/* 块级公式包装器 */
.display-formula {
  display: block;
  text-align: center;
}
</style>
